package com.example.demo.util;

import com.example.demo.constant.ResponseCode;
import com.example.demo.exception.DemoServiceException;
import com.example.demo.vo.ApiResult;

/**
 *@Description 统一返参工具类
 *@Author Levi
 *@Date 2019/4/23-14:14
*/
public class ResultUtil {
    public static <T> ApiResult<T> error(int code, String msg){
        ApiResult<T> result = new ApiResult();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
    public static <T> ApiResult<T> error(ResponseCode responseCode){
        ApiResult<T> result = new ApiResult();
        result.setCode(responseCode.getCode());
        result.setMsg(responseCode.getMsg());
        return result;
    }

    public static <T> ApiResult<T> success(T t){
        ApiResult<T> result=new ApiResult();
        result.setCode(ResponseCode.SUCCESS.getCode());
        result.setMsg(ResponseCode.SUCCESS.getMsg());
        result.setData(t);
        return result;
    }

    public static <T> T getSuccessData(ApiResult<T> result) throws Exception {
        if(result.getCode() != ResponseCode.SUCCESS.getCode()){
            throw new DemoServiceException(result.getCode() ,result.getMsg());
        }else{
            return result.getData();
        }
    }
}
